package org.devocean.groupbuying.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.CommentDAO;
import org.devocean.groupbuying.domain.Comment;
import org.springframework.stereotype.Repository;

@Repository
public class CommentDAOImpl implements CommentDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Comment> findAllComments() {
		return em.createQuery("select c from Comment c").getResultList();
	}

	public long countComment() {
		return em.createQuery("select count(c) from Comment c", long.class)
				.getSingleResult();
	}

	public Comment findCommentById(Integer id) {
		return em.find(Comment.class, id);
	}

	public void deleteComment(int id) {
		final Comment comment = em.find(Comment.class, id);
		if (comment != null) {
			em.remove(comment);
		}

	}

	public Comment saveComment(Comment comment) {
		em.persist(comment);
		return comment;
	}

	public Comment updateComment(Comment comment) {
		em.merge(comment);
		return comment;
	}

	public List<Comment> findCommentsByCustomer(Integer customerID) {
		return em
				.createQuery(
						"SELECT c FROM Comment c WHERE c.customer.customerID =:cid",
						Comment.class).setParameter("cid", customerID)
				.getResultList();

	}

	public List<Comment> findCommentsByCustomer(Integer customerID, String lang) {

		return em
				.createQuery(
						"SELECT c FROM Comment c "
								+ " WHERE c.customer.customerID =:cid",
						Comment.class).setParameter("cid", customerID)
				.getResultList();
	}

	public Long countCommentByCustomer(Integer customerID) {

		return em
				.createQuery(
						"select COUNT(c) from Comment c "
								+ "WHERE c.customer.customerID =:cid",
						Long.class).setParameter("cid", customerID)
				.getSingleResult();
	}

}
